package com.cs.disposition.mqtt;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.stereotype.Service;

@Service
public class MqttService {
    @Resource
    private MqttClient mqttClient;

    @PostConstruct
    public void subscribe() {
        try {
            mqttClient.subscribe("test/topic");
        } catch (Exception ignored) {
        }
    }


    public void subscribe(String topic) throws MqttException {
        if (mqttClient != null && mqttClient.isConnected()) {
            mqttClient.subscribe(topic);
        }
    }

    public void publish(String topic, String payload) throws MqttException {
        if (mqttClient != null && mqttClient.isConnected()) {
            MqttMessage message = new MqttMessage(payload.getBytes());
            mqttClient.publish(topic, message);
        }
    }

    public void publish(String topic, byte[] payload) throws MqttException {
        if (mqttClient != null && mqttClient.isConnected()) {
            MqttMessage message = new MqttMessage(payload);
            mqttClient.publish(topic, message);
        }
    }

    public void disconnect() throws MqttException {
        if (mqttClient != null && mqttClient.isConnected()) {
            mqttClient.disconnect();
        }
    }
}
